from . import db, login_manager
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)
    email = db.Column(db.String(120), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    
    @property
    def password(self):
        raise AttributeError('password is not a readable attribute')
        
    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)
        
    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

@login_manager.user_loader
def load_user(id):
    return User.query.get(int(id))

class Device(db.Model):
    __tablename__ = 'devices'
    
    id = db.Column(db.Integer, primary_key=True)
    device_id = db.Column(db.String(64), unique=True, index=True)
    name = db.Column(db.String(64))
    device_type = db.Column(db.String(32))
    location = db.Column(db.String(128))
    status = db.Column(db.String(32), default='offline')
    last_online = db.Column(db.DateTime, default=datetime.utcnow)
    description = db.Column(db.Text)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

class WaterQuality(db.Model):
    __tablename__ = 'water_quality'
    id = db.Column(db.Integer, primary_key=True)
    device_id = db.Column(db.Integer, db.ForeignKey('devices.id'), index=True)
    ph = db.Column(db.Float)
    turbidity = db.Column(db.Float)  # 浊度
    dissolved_oxygen = db.Column(db.Float)  # 溶解氧
    conductivity = db.Column(db.Float)  # 电导率
    temperature = db.Column(db.Float)  # 温度
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)
    
    device = db.relationship('Device', backref=db.backref('water_quality_records', lazy='dynamic'))

    def to_dict(self):
        return {
            'id': self.id,
            'device_id': self.device_id,
            'ph': self.ph,
            'turbidity': self.turbidity,
            'dissolved_oxygen': self.dissolved_oxygen,
            'conductivity': self.conductivity,
            'temperature': self.temperature,
            'timestamp': self.timestamp.strftime('%Y-%m-%d %H:%M:%S')
        }

class PipeNetwork(db.Model):
    __tablename__ = 'pipe_networks'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True, index=True)
    pipe_type = db.Column(db.String(32))  # 管道类型：主管、支管等
    material = db.Column(db.String(32))  # 管道材质
    diameter = db.Column(db.Float)  # 管径(mm)
    length = db.Column(db.Float)  # 长度(m)
    start_point = db.Column(db.String(128))  # 起点位置
    end_point = db.Column(db.String(128))  # 终点位置
    installation_date = db.Column(db.Date)  # 安装日期
    status = db.Column(db.String(32), default='normal')  # 状态：正常、维修、报废等
    description = db.Column(db.Text)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

class MaintenanceRecord(db.Model):
    __tablename__ = 'maintenance_records'
    id = db.Column(db.Integer, primary_key=True)
    pipe_id = db.Column(db.Integer, db.ForeignKey('pipe_networks.id'), index=True)
    maintenance_type = db.Column(db.String(32))  # 维护类型：检查、维修、更换等
    maintenance_date = db.Column(db.DateTime, default=datetime.utcnow)
    description = db.Column(db.Text)  # 维护描述
    operator = db.Column(db.String(64))  # 操作人员
    status = db.Column(db.String(32))  # 维护状态：已完成、进行中等
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    pipe = db.relationship('PipeNetwork', backref=db.backref('maintenance_records', lazy='dynamic'))

class UserNotificationSettings(db.Model):
    __tablename__ = 'user_notification_settings'
    
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)
    device_offline = db.Column(db.Boolean, default=True)
    device_error = db.Column(db.Boolean, default=True)
    water_quality = db.Column(db.Boolean, default=True)
    water_pressure = db.Column(db.Boolean, default=True)
    maintenance_reminder = db.Column(db.Boolean, default=True)
    inspection_reminder = db.Column(db.Boolean, default=True)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    user = db.relationship('User', backref=db.backref('notification_settings', uselist=False))

class SystemSettings(db.Model):
    __tablename__ = 'system_settings'
    
    id = db.Column(db.Integer, primary_key=True)
    # 水质阈值设置
    ph_min = db.Column(db.Float, default=6.5)  # pH最小值
    ph_max = db.Column(db.Float, default=8.5)  # pH最大值
    turbidity_threshold = db.Column(db.Float, default=5.0)  # 浊度阈值
    
    # 设备监控设置
    offline_threshold = db.Column(db.Integer, default=5)  # 设备离线判定时间（分钟）
    data_collection_interval = db.Column(db.Integer, default=30)  # 数据采集间隔（秒）
    
    # 维护计划设置
    routine_inspection_interval = db.Column(db.Integer, default=7)  # 常规检查间隔（天）
    full_maintenance_interval = db.Column(db.Integer, default=30)  # 全面维护间隔（天）
    
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    @classmethod
    def get_settings(cls):
        """获取系统设置，如果不存在则创建默认设置"""
        settings = cls.query.first()
        if not settings:
            settings = cls()
            db.session.add(settings)
            db.session.commit()
        return settings 